package algorithms.threadpool;

import java.util.Objects;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class PoolGetNumTest {
    public static void main(String[] args) throws InterruptedException {
        // 处理100
        threadPool(10000.7);

    }

    private static void threadPool(double n) throws InterruptedException {

        // 自定义线程池
        ExecutorService pool = new ThreadPoolExecutor(10,
                15,
                5,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(),
                new ThreadPoolExecutor.CallerRunsPolicy());

        // 开始执行任务
        System.out.println("开始执行任务。。。");
        //AtomicInteger atomicInteger = new AtomicInteger();
        ConcurrentHashMap<String, Double> threadMap = new ConcurrentHashMap<>();
        ThreadLocal<Double> local = new ThreadLocal<>();
        double sum = 0.0;
        for (double i = 1.0; i < n + 1; i++) {
            sum += i;
            double num = i;
            pool.execute(() -> {
                local.set(num);
                try {
                    // 随机睡眠 模拟执行任务
                    TimeUnit.MILLISECONDS.sleep( (int)(Math.random()*100+1));
                } catch (InterruptedException e) {
                    System.err.println("线程睡眠失败！");
                }
                String name = Thread.currentThread().getName();
                System.out.println("线程:" + name
                        + "==>获取到元素：" + local.get());
                Double threadSum = threadMap.get(name);
                if(Objects.isNull(threadSum)) {
                    threadMap.put(name,local.get());
                } else {
                    threadMap.put(name,threadSum + local.get());
                }
                local.remove();
            });
        }
        TimeUnit.SECONDS.sleep(5);
        pool.shutdown();
        while (!pool.isTerminated()) ;
        System.out.println("总和："+sum);
        System.out.println("线程map总和："+threadMap.values().stream().mapToDouble(e->e).sum());
    }
}
